package org.zebra.mybatis.plus.ext.redundancy;

import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.zebra.mybatis.plus.ext.redundancy.description.WaitUpdateDescription;
import org.zebra.mybatis.plus.ext.redundancy.event.EntityUpdateEvent;
import org.zebra.mybatis.plus.ext.redundancy.signature.DescriptionSignature;

import java.util.Map;

/**
 * @author zhanghongbin
 */
public class RedundancyFieldEventRegister {

    @Async
    @EventListener
    public void onApplicationEvent(EntityUpdateEvent<?> entityUpdateEvent) {

        Map<DescriptionSignature, WaitUpdateDescription> waitUpdateEntityDescGroupByCondition =
                RedundancyFieldManager.ENTITY_GROUP_CACHE_MAP.get(entityUpdateEvent.getEntityName());
        if (waitUpdateEntityDescGroupByCondition == null) {
            return;
        }

        // 针对分好组的数据，做分组批量更新(提升性能，同一个类下多个属性冗余了同一个源下的多个属性的情况)
        for (WaitUpdateDescription waitUpdateDescription : waitUpdateEntityDescGroupByCondition.values()) {
            // 待更新的字段
            RedundancyFieldManager.executeUpdate(entityUpdateEvent, waitUpdateDescription);
        }
    }
}
